package com.contatos.control;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import java.sql.Statement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * User: Christian
 * Date: 01/05/14
 * Time: 20:46
 * To change this template use File | Settings | File Templates.
 */
public class DataAccessObject {
    private MysqlDataSource dataSource;
    private String DB_NAME = "mirocostin_4";
    private String DB_URL = "dbmy0100.whservidor.com";
    private int DB_PORT = 3306;
    private String DB_USER = "mirocostin_4";
    private String DB_PSSW = "utfpr2014";
    private Connection connection = null;

    public DataAccessObject(){
        dataSource = new MysqlDataSource();
        dataSource.setDatabaseName(DB_NAME);
        dataSource.setServerName(DB_URL);
        dataSource.setPortNumber(DB_PORT);
        dataSource.setUser(DB_USER);
        dataSource.setPassword(DB_PSSW);
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            System.err.println(e.getMessage());
        }
    }

    public int executeUpdate(String sql){
       int result = 0;
        try {
            Statement statement = connection.createStatement();
            result = statement.executeUpdate(sql);
        } catch (SQLException e) {
            System.err.println(e.getMessage());
        }
        return result;
    }

    public void closeConnection(){
        try {
            connection.close();
        } catch (SQLException e) {
            System.err.println(e.getMessage());
        }

    }

    public ResultSet executeQuery(String sql){
        ResultSet resultSet = null;
        try {
            Statement statement = connection.createStatement();
            resultSet = statement.executeQuery(sql);
        } catch (SQLException e){
            System.err.println(e.getMessage());
        }
        return resultSet;
    }

}
